package com.zang.array;

/**
 * @author ZVerify
 * @since 2022/10/09 19:04
 * @see <a href="https://leetcode.cn/problems/ju-zhen-zhong-de-lu-jing-lcof/submissions/">...</a>
 **/
public class 矩阵中的路径 {
    public boolean exist(char[][] board, String word) {

        char[] array = word.toCharArray();

        int K = board[0].length;
        int T = board.length;

        for (int i = 0; i < T; i++) {
            for (int j = 0; j < K; j++) {
                if (dfs(board,array,i,j,0)) return true;
            }
        }

        return false;
    }

    boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        if(i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]) return false;
        if(k == word.length - 1) return true;
        board[i][j] = '\0';
        boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
                dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i , j - 1, k + 1);
        board[i][j] = word[k];
        return res;
    }
}
